import store from '@/store'; 

import { getToken } from '@/utils/utils'
import { whiteList } from './constantRouter'
import qs from 'qs'

const loginPath = '/login'
const defultPath = '/'

//获取第一个路由
function getFirstRoutePath(routers){
  if(routers == null || routers.length == 0){
      return null;
  }
  for(let i=0; i<routers.length;i++){
    if(!routers[i].hidden && routers[i].path){
      return routers[i].path;
    }
    if(routers[i].children && routers[i].children.length > 0){
      let first = getFirstRoutePath(routers[i].children);
      if(first){
          return first;
      }
    }
  }
}

// 权限验证
export function createRouterGuard(router){
  
  router.beforeEach(async (to, from, next) => {
    //登录页面判断当前是否是登录状态，如果是直接跳转回首页或者backUrl
    if(to.path.startsWith(loginPath)){
      const token = getToken();
      if(token){
        const query = qs.parse(location.search.substring(1));
        if (query.backUrl) {
            let backUrl = decodeURIComponent(query.backUrl);
            window.location = backUrl + (backUrl.indexOf('?') >= 0 ? '&' : '?') + 'token=' + token;
        } else {
          next(defultPath);
        }
      }else{
        next();
      }
    }else{
      if(whiteList.includes(to.path)){
        // 无需登录的页面 直接访问即可
        next();
      }else{
        if (getToken()) {
          //此时判断有没有加载过动态路由（后端菜单那种）
          if(!store.state.user.routesLoaded){
            const routers = await store.dispatch('user/setRouters');
            routers.forEach(r => {
              router.addRoute('main', r);
            });
            //router.addRoute({ path: '/:path(.*)*', redirect: '/404' });
            store.commit('user/SET_ROUTES_LOADED', true);
            if (to.name == '404' && to.fullPath) {
              next({ path: to.fullPath, replace: true });
            } else {
              if(to.path == defultPath){
                let first = getFirstRoutePath(routers);
                if(first){
                  next({ path: first, replace: true });
                  return;
                }
              }
              next({ ...to, replace: true });
            }
          }else{
            if(to.path == defultPath){
              let first = getFirstRoutePath(routers);
              if(first){
                next({ path: first, replace: true });
                return;
              }
            }
            next();
          }
        } else {
          next(loginPath);
        }
      }
    }
  })
}